package com.houhanzhi.util;

import com.houhanzhi.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;

@Slf4j
public class JWTUtil {

    /**
     * 主题
     */
    private static final String SUBJECT = "short_link";
    /**
     * 加密密钥
     */
    private static final String SECRET = "hhz.short_link";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "pre_short_link";

    /**
     * 过期时间,7天
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;

    /**
     * 根据用户信息，生成令牌
     *
     * @param user
     * @return
     */
    public static String geneJsonWebToken(LoginUser user) {

        if (Objects.isNull(user)) {
            throw new NullPointerException("对象为空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("account_no", user.getAccountNo())
                .claim("username", user.getUsername())
                .claim("phone", user.getPhone())
                .claim("mail", user.getMail())
                .claim("auth", user.getAuth())
                .setIssuedAt(new Date()) // 发布时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) // 过期时间
                .signWith(SignatureAlgorithm.HS256, SECRET).compact(); // 签名

        token = TOKEN_PREFIX + token;

        return token;
    }

    /**
     * 校验token的方法(解密)
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {

            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();

            return claims;

        } catch (Exception e) {
            log.info("jwt解密失败");
            return null;
        }

    }
}
